import random
from datetime import datetime
from string import ascii_lowercase
import requests
import urllib3
from selenium.webdriver.remote.webdriver import WebDriver
from configs.settings import API_URL
from libraries.logger import log

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def _cookie_to_selenium_format(cookies) -> list:
    """cookie格式转换"""
    return [
        {'path': '/', 'secure': False, 'name': name, 'value': value, 'expires': ''} for name, value in cookies.items()
    ]


def _login(email, password):
    """api用户登录"""
    data = {"email": email, "password": password}
    response = requests.post(url=API_URL + '1.0/user/login', json=data, verify=False)
    log.info(f"通过api登录用户，email：{email} status_code：{response.status_code}")
    if response.status_code != 200:
        return _login(email, password)
    token, user_id, has_login = response.json()['data']['token'], response.json()['data']['user_id'], '1'
    all_cookies = dict(response.cookies)
    all_cookies['user_id'] = str(user_id)
    all_cookies['hasLogin'] = has_login
    return all_cookies, email, token


def _register():
    """api用户注册"""
    random_email = f"WebTest{datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')}{''.join(random.sample(ascii_lowercase, 8))}@tetx.com"
    data = {"email": random_email, "name": random_email[:-9], "password": '123456', "wedding_date": ""}
    response = requests.post(url=API_URL + '1.0/user/register', json=data, verify=False)
    log.info(f"通过api注册用户，email：{random_email} status_code：{response.status_code}")
    if response.status_code != 200:
        return _register()
    token, user_id, has_login = response.json()['data']['token'], response.json()['data']['user_id'], '1'
    all_cookies = dict(response.cookies)
    all_cookies['user_id'] = str(user_id)
    all_cookies['hasLogin'] = has_login
    return all_cookies, random_email, token


def _cookies_set(cookies, driver: WebDriver):
    """浏览器cookies设置"""
    cookies = _cookie_to_selenium_format(cookies)
    driver.delete_cookie('hasLogin')
    driver.delete_cookie('user_id')
    driver.delete_cookie('AZSID')
    driver.delete_cookie('__cfduid')
    driver.delete_cookie('_shop_cart')
    driver.delete_cookie('shoppingCartGoodsTotal')
    for cookie in cookies:
        driver.add_cookie(cookie)
    driver.refresh()
    log.info(f"浏览器用户状态: {driver.get_cookie('hasLogin')}")


def api_login(email, password, driver: WebDriver):
    """api登录"""
    login_info = _login(email, password)
    _cookies_set(login_info[0], driver)
    return login_info[1], login_info[2]


def api_register(driver: WebDriver):
    """api注册"""
    register_info = _register()
    _cookies_set(register_info[0], driver)
    return register_info[1], register_info[2]
